package com.bwie.auth.service.impl;

import cn.hutool.http.server.HttpServerRequest;
import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.AuthFeign;
import com.bwie.auth.service.AuthService;
import com.bwie.auth.utils.DelayedQueue;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.po.UserPo;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.domain.vo.UserVo;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.apache.el.parser.Token;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthFeign authFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private DelayedQueue delayedQueue;



    /**
     * 登录
     */
    @Override
    public Result<UserResponse> login(UserVo userVo) {
        String userName = userVo.getUserName();
        String userPwd = userVo.getUserPwd();
        if(StringUtils.isAnyBlank(userName,userPwd)){
            Result.error("用户名或者密码不能为空");
        }
        Result<UserPo> login = authFeign.login(userName);
        UserPo userPo = login.getData();

        HashMap<String, Object> claims = new HashMap<>();
        String usekey = UUID.randomUUID().toString();
        claims.put(JwtConstants.USER_KEY,usekey);
        String token = JwtUtils.createToken(claims);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+usekey, JSONObject.toJSONString(userPo),30, TimeUnit.MINUTES);
        UserResponse userResponse = new UserResponse();
        userResponse.setToken(token);
        userResponse.setLasttime("30MIN");
        delayedQueue.sendDelayedQueue("qq",userResponse,30);
        return Result.success(userResponse,"登录成功");
    }

    /**
     * 获取info
     */
    @Override
    public UserPo getInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String UserJSONStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        UserPo userPo = JSONObject.parseObject(UserJSONStr, UserPo.class);
        return userPo;
    }
}
